<template>
	<view>
		<view class="searchbar_view" :style="{backgroundColor: bgColor}">
			<uni-search-bar class="searchbar" :style="{backgroundColor: bgColor}" :placeholder="placeholder"
				bgColor="#FFF" cancelButton="none" maxlength="20" @confirm="search" @input="input">
			</uni-search-bar>
			<view class="row">
				<slot name='button'>
					<button class="button" v-for="(item,index) in buttons" :style="[buttonStyle(index)]" :key="index"
						:data-item="item" @click.stop="buttonClicked($event,item,index)">{{item}}</button>
				</slot>
			</view>
		</view>
		<view v-if="showTips" class="tips">
			<slot name='tips'>
				<text v-if="!markNumRed">{{tips}}</text>
				<template v-else>
					<text v-for="(item, index) in tipsTextArray" :key="index" :class="index % 2 === 0 ? '' : 'num'">
						{{ item }}
					</text>
				</template>
			</slot>
		</view>
	</view>
</template>

<script>
	export default {
		name: 'cs-searchbar',
		props: {
			showTips: {
				type: Boolean,
				default: false
			},
			tips: {
				type: String,
				default: ''
			},
			buttons: {
				type: Array,
				default () {
					return [];
				}
			},
			buttonStyles: {
				type: [Array, Object],
				default () {
					return []
				}
			},
			placeholder: {
				type: String,
				default: '搜索'
			},
			bgColor: {
				type: String,
				default: "#FFFFFF"
			},
			markNumRed: {
				type: Boolean,
				default: true
			}
		},
		data() {
			return {

			}
		},
		computed: {
			tipsTextArray() {
				let titleText = this.tips
					.replace(/\d+/g, (str) => "<sp>" + str + "<sp>")
					.split("<sp>");
				return titleText;
			}
		},
		methods: {
			buttonClicked(e, item, index) {
				this.$emit('searchbar_btnClicked', e.target.dataset.item, index)
			},
			search(e) {
				this.$emit('searchbar_search')
			},
			input(e) {
				this.$emit('input', e.value)
				this.$emit('searchbar_input', e)
			},
			buttonStyle(index) {
				if (this.$validator.method.isObj(this.buttonStyles)) {
					return this.buttonStyles || {};
				}
				if (Array.isArray(this.buttonStyles) && index < this.buttonStyles.length) {
					return this.buttonStyles[index] || {};
				}
				return {};
			}
		}
	}
</script>

<style>
	.searchbar_view {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
	}

	.row {
		display: flex;
		flex-direction: row;
		justify-content: flex-start;
		align-items: center;
	}

	.searchbar {
		flex: 1;
	}


	button {
		padding: 0;
		margin: 0;
	}

	button::after {
		border: none;
	}

	.row .button {
		font-size: 14px;
		margin-right: 5px;
		padding-left: 7px;
		padding-right: 7px;
		background-color: #078DED;
		color: #FFFFFF;
		border-radius: 3px;
		line-height: 28px;
		height: 28px;
	}

	.tips {
		padding: 0px 8px;
		margin-top: -2px;
	}

	.tips .num {
		color: red;
	}
</style>
